package cn.itcast.fore.action;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import org.springframework.data.domain.Page;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/** 
 * action的包装类
 *
 * @author Shao-Fei Fan 
 * @version 1.0,2017年9月4日 下午10:38:22 
 */
public abstract  class BaseAction<T> extends ActionSupport implements ModelDriven<T>{
	
	protected T model;
	
	@Override
	public T getModel() {
		return model;
	}
	
	// 通过构造参数实例化T
	public BaseAction() {
		ParameterizedType parameterizedType = (ParameterizedType)this.getClass().getGenericSuperclass();
		Class<T> type = (Class<T>) parameterizedType.getActualTypeArguments()[0];
		try {
			model = type.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("模型实例化错误");
		}
	}
	
	// 分页的方法的提取
	protected int page;
	protected int rows;
	
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	
	/**
	 * 封装分页数据为map并压到值栈中，转为json
	 * @param page
	 */
	protected void pushPageDataToVolueStake(Page<T> page){
		// 封装map
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("total", page.getTotalElements());
		map.put("rows", page.getContent());
		
		ServletActionContext.getContext().getValueStack().push(map);
	}
	
	
}
